package com.enfi.api.modules.ext.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.enfi.api.domain.res.ApiResult;
import com.enfi.api.modules.ext.mq.common.MessageTypeEnum;
import com.enfi.api.modules.ext.mq.common.MqConstants;
import com.enfi.api.modules.ext.mq.config.RabbitMqConfiguration;
import com.enfi.api.modules.ext.mq.provider.FanoutProvider;
import com.enfi.api.modules.ext.service.MqBzService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


/**
 * @author xukk
 * @date 2020/3/10
 */
@Service
@Slf4j
public class MqBzServiceImpl implements MqBzService {
    private FanoutProvider fanoutProvider;


    @Override
    public ApiResult resolve(JSONObject jsonObject) {
        log.warn("http传过来数据:{}",jsonObject.toString());
        MessageTypeEnum messageType = MessageTypeEnum.convert(jsonObject.getString(MqConstants.ST.MESSAGE_TYPE));
        if(jsonObject.getString("type")!=null){
            messageType= MessageTypeEnum.convert(jsonObject.getString("type"));
        }
        try {
            switch (messageType) {
                case NOTICE:
                    fanoutProvider.send(jsonObject.toJSONString(), RabbitMqConfiguration.FANOUT_NOTICE_EXCHANGE);
                    break;
                case GTASKS:
                    fanoutProvider.send(jsonObject.toJSONString(), RabbitMqConfiguration.FANOUT_GTASKS_EXCHANGE);
                    break;
                case REPORT:
                    fanoutProvider.send(jsonObject.toJSONString(), RabbitMqConfiguration.FANOUT_REPORT_EXCHANGE);
                    break;
                case FEEDBACK:
                    fanoutProvider.send(jsonObject.toJSONString(), RabbitMqConfiguration.FANOUT_FEEDBACK_EXCHANGE);
                    break;
                default:
                    String isDefault=jsonObject.getString(MqConstants.ST.IS_DEFAULT);
                    if(StringUtils.hasText(isDefault)&&isDefault.equalsIgnoreCase(Integer.valueOf(1).toString())){
                        fanoutProvider.send(jsonObject.toJSONString(), RabbitMqConfiguration.FANOUT_DEFAULT_EXCHANGE);
                    }else {
                        return ApiResult.renderError("type类型无法解析");
                    }
            }
        } catch (Exception e) {
            return ApiResult.renderError(e.getMessage());
        }
        return ApiResult.renderOk();

    }

    @Autowired
    public void setFanoutSender(FanoutProvider fanoutProvider) {
        this.fanoutProvider = fanoutProvider;
    }
}
